package com.example.service.impl;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.dto.weixiubaoyang.MoldApplyDto;
import com.example.entity.dto.weixiubaoyang.MoldDto;
import com.example.entity.mysql.MoldAllocationDetail;
import com.example.entity.mysql.MoldAllocationHeader;
import com.example.entity.vo.CommonPageVo;
import com.example.entity.vo.MoldAllocationDetailVo;
import com.example.entity.vo.MoldAllocationPrintVo;
import com.example.entity.vo.MoldAllocationVo;
import com.example.exception.CustomException;
import com.example.mapper.MoldAllocationDetailMapper;
import com.example.mapper.MoldAllocationHeaderMapper;
import com.example.mapper.pc.ResourceMapper;
import com.example.service.MoldAllocationHeaderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiangPandeng
 * @since 2024-11-27
 */
@Service
public class MoldAllocationHeaderServiceImpl extends ServiceImpl<MoldAllocationHeaderMapper, MoldAllocationHeader> implements MoldAllocationHeaderService {

    @Autowired
    private MoldAllocationDetailMapper moldAllocationDetailMapper;

    @Autowired
    private MoldAllocationHeaderMapper moldAllocationHeaderMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    //查询
    @Override
    public CommonPageVo<MoldAllocationVo> getMoldAllocationVo(MoldDto moldDto) {
        List<MoldAllocationVo> list = new ArrayList<>();
        PageHelper.startPage(moldDto.getPageNum(), moldDto.getPageSize());
        PageInfo<MoldAllocationHeader> pageInfo =new PageInfo<>(moldAllocationHeaderMapper.selectHeader(moldDto));
        Long total = pageInfo.getTotal();
        //查询单头信息
        List<MoldAllocationHeader> headerlist = pageInfo.getList();

        //查询单身信息
        List<MoldAllocationDetail> detaillist = moldAllocationDetailMapper.selectDetail(moldDto);

        for (MoldAllocationHeader moldAllocationHeader : headerlist){
            int serial=1;
            String orderType = moldAllocationHeader.getOrderType();
            String orderNumber = moldAllocationHeader.getOrderNumber();
            //通过moldAllocationHeader的单号单别查找在detaillist里具有相同单别，单号的单身列表
            List<MoldAllocationDetailVo> detailVos=new ArrayList<>();
            for (MoldAllocationDetail detail : detaillist) {
                if (detail.getOrderType().equals(orderType) && detail.getOrderNumber().equals(orderNumber)){
                    MoldAllocationDetailVo vo=new MoldAllocationDetailVo();
                    BeanUtils.copyProperties(detail,vo);
                    vo.setSerial(serial++);
                    detailVos.add(vo);
                }
            }
            MoldAllocationVo moldAllocationVo=new MoldAllocationVo();
            BeanUtils.copyProperties(moldAllocationHeader,moldAllocationVo);
            moldAllocationVo.setMoldAllocationDetails(detailVos);
            list.add(moldAllocationVo);
        }
        return new CommonPageVo<MoldAllocationVo>().setResult(list).setTotal(total);
    }

    @Override
    public String updateMoldAllocationHeader(MoldApplyDto moldApplyDto) {
//        //查询本来的单头
//        LambdaQueryWrapper<MoldAllocationHeader> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(MoldAllocationHeader::getOrderType, moldApplyDto.getOrderType())
//                .eq(MoldAllocationHeader::getOrderNumber, moldApplyDto.getOrderNumber());
//        MoldAllocationHeader exist = moldAllocationHeaderMapper.selectOne(wrapper);
//        if (exist.getCompletionCode().equals("Y")||exist.getCompletionCode().equals("V")){
//            throw new RuntimeException("单头已审核，请勿重复操作");
//        }
//        //修改单头
//        Integer num1 = moldAllocationHeaderMapper.updateCode(moldApplyDto);
//
//        //修改单身
//        Integer num2 =moldAllocationDetailMapper.updateCode(moldApplyDto);
//
//        //查询每一个单身
//        LambdaQueryWrapper<MoldAllocationDetail> wrapper1 = new LambdaQueryWrapper<>();
//        wrapper1.eq(MoldAllocationDetail::getOrderType, "1218")
//                .eq(MoldAllocationDetail::getOrderNumber, moldApplyDto.getOrderNumber());
//        List<MoldAllocationDetail> moldAllocationDetails = moldAllocationDetailMapper.selectList(wrapper1);
//        Integer num3=0;
//        for (MoldAllocationDetail moldAllocationDetail:moldAllocationDetails) {
//            if (moldApplyDto.getApprovalCode().equals("Y")){
//                //改变原有地址
//                num3 = resourceMapper.updateStorageLocation(moldAllocationDetail);
//            }
//        }
//        return "改变单头："+num1+"改变单身"+num2+"改变地址"+num3;
        return null;
    }

    @Override
    @DSTransactional
    public void updateStatus(Integer id, Integer type) {
        MoldAllocationHeader header = moldAllocationHeaderMapper.selectById(id);
        if (header==null)
            throw new CustomException("500","不存在的信息");
        switch (type){
            case 0: {
                //作废，修改状态为R即可
                header.setStatus("R");
                break;
            }
            case 1:{
                //收货方确认收货，此状态只能在状态为审核成功后即Y的时候才可以改变状态为T，并将调拨单中的确认收货日receiveDate字段填上
                if (!header.getStatus().equals("Y"))
                    throw new CustomException("500","审核成功后才可以确认收货!");
                header.setStatus("T");
                this.lambdaUpdate().eq(MoldAllocationHeader::getOrderType,header.getOrderType())
                        .eq(MoldAllocationHeader::getOrderNumber,header.getOrderNumber())
                        .set(MoldAllocationHeader::getReceiveDate, LocalDateTime.now().toString().replaceAll("-",""))
                        .update();
                break;
            }
            case 2:{
                //取消收货，和确认收货相反，将状态改为Y，并将收货日期设置为空
                if (!header.getStatus().equals("T"))
                    throw new CustomException("500","状态异常!");
                header.setStatus("Y");
                this.lambdaUpdate().eq(MoldAllocationHeader::getOrderType,header.getOrderType())
                        .eq(MoldAllocationHeader::getOrderNumber,header.getOrderNumber())
                        .set(MoldAllocationHeader::getReceiveDate, null)
                        .update();
                break;
            }
            default:
                throw new CustomException("500","未知状态!");
        }
        this.updateById(header);
    }

    @Override
    public MoldAllocationPrintVo print(String orderNumber) {
        String orderType = "MT";
        MoldAllocationHeader one = this.lambdaQuery().eq(MoldAllocationHeader::getOrderType, orderType)
                .eq(MoldAllocationHeader::getOrderNumber, orderNumber).one();
        if (one==null) return null;
        MoldAllocationPrintVo vo = new MoldAllocationPrintVo();
        BeanUtils.copyProperties(one,vo);
        vo.setPrintDate(LocalDateTime.now());
        AtomicInteger serial = new AtomicInteger(1);
        List<MoldAllocationDetailVo> detailVos = moldAllocationDetailMapper.selectList(new LambdaQueryWrapper<MoldAllocationDetail>()
                .eq(MoldAllocationDetail::getOrderType, orderType)
                .eq(MoldAllocationDetail::getOrderNumber, orderNumber)
        ).stream().map(item -> {
            MoldAllocationDetailVo vo1 = new MoldAllocationDetailVo();
            BeanUtils.copyProperties(item, vo1);
            vo1.setSerial(serial.getAndAdd(1));
            return vo1;
        }).collect(Collectors.toList());
        return vo.setMoldAllocationDetails(detailVos);
    }

}
